package com.alan.weather.filter;

import com.alan.weather.common.responseResult.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {


    //路径匹配器(支持通配符)
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1. 请求的路径
        String uri = request.getRequestURI();
        //2. 定义放行的路径
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };
        //3. 检查当前路径是否放行
        boolean checked = check(uri, urls);

        if (checked){
            filterChain.doFilter(request,response);
            return;
        }else {
            // 不在放行名单中，检查用户是否登录
            Object employee = request.getSession().getAttribute("employee");
            if (!ObjectUtils.isEmpty(employee)){
                filterChain.doFilter(request,response);
                return;
            }else {
                // 通过输出流告诉页面未登录
                response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
                return;
            }

        }
    }


    private boolean check(String uri, String[] urls) {
        for (String url : urls) {
//            if (PATH_MATCHER.match(uri,url)) return true;
            if (PATH_MATCHER.match(url,uri)) return true;
        }
        return false;
    }
}
